package com.uniledger.exchange.home.scheme;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.uniledger.commonlib.easymoney.EasyMoneyEditText;
import com.uniledger.commonlib.easymoney.EasyMoneyTextView;
import com.uniledger.commonlib.easymoney.IconMoneyEditText;
import com.uniledger.commonlib.numberkeyboard.KeyboardUtil;
import com.uniledger.commonlib.pinkeyboard.IKeyboardListener;
import com.uniledger.commonlib.pinkeyboard.KeyboardDialog;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.R;
import com.uniledger.exchange.bank.AddBankActivity;
import com.uniledger.exchange.bank.BankCard;
import com.uniledger.exchange.bank.BottomBankAdapter;
import com.uniledger.exchange.bank.BottomSelectDialog;
import com.uniledger.exchange.bank.Gateway;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.glide.GlideApp;
import com.uniledger.exchange.home.HomeCenter;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.StellarList;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.uniledger.exchange.stellar.TransactionUtils;

import org.reactivestreams.Publisher;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import static com.uniledger.commonlib.bigdecimalutils.BigDecimalUtils.is;


/**
 * 余额提现页面
 */
public class WithdrawActivity extends BaseActivity implements BottomSelectDialog.OnSelectBankListener, IKeyboardListener {

    @BindView(R.id.cardName)
    TextView cardName;

    @BindView(R.id.cardNumber)
    TextView cardNumber;

    @BindView(R.id.layout_bank)
    RelativeLayout bankSelected;

    @BindView(R.id.txt_wallet_balance)
    EasyMoneyTextView walletBalance;

    @BindView(R.id.txt_all)
    TextView withdrawAll;

    @BindView(R.id.edit_amount)
    IconMoneyEditText iconMoneyEditText;

    EasyMoneyEditText editAmount;

    @BindView(R.id.txt_fee)
    TextView txtFee;

    @BindView(R.id.txt_pay_balance)
    EasyMoneyTextView txtPayBalance;

    @BindView(R.id.btn_confirm)
    Button confirm;

    @BindView(R.id.cardIcon)
    ImageView cardIcon;

    @BindView(R.id.label_reminders)
    TextView label_reminders;

    @BindString(R.string.withdraw_label_hint)
    String reminderHint;

    @BindString(R.string.withdraw_label_zero_hint)
    String zeroHint;

    KeyboardUtil keyboardUtil;

    BottomSelectDialog bankDialog;

    BottomBankAdapter bankAdapter;

    String currency;//当前钱包资产符号
    String coinPair;//币对
    BigDecimal rateBigDecimal;
    BigDecimal totalBalanceBigDecimal;
    BankCard bankCard;

    @BindString(R.string.withdraw_fee)
    String feeStr;

    KeyboardDialog pinDialog;

    boolean isPay;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, WithdrawActivity.class);
        activity.startActivity(intent);
    }

    @BindString(R.string.withdraw_bar_title)
    String title;

    @Override
    public void initBar() {
        super.initBar();
        toolbar.setTitle(title);
    }

    public void showPayKeyBoard() {
        keyboardUtil.hideKeyboard();
        if (pinDialog == null) {
            pinDialog = new KeyboardDialog(this);
            pinDialog.setKeyboardListener(this);
        }
        pinDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdraw);

        editAmount = iconMoneyEditText.getMoneyEditText();
        iconMoneyEditText.setSymbol(R.drawable.ic_common_aed);

        bankDialog = new BottomSelectDialog(this, getSupportFragmentManager());
        bankDialog.init();
        bankDialog.setSelectBankListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            confirm.setStateListAnimator(null);
        }

        keyboardUtil = new KeyboardUtil(this, false);
        keyboardUtil.setOnOkClick(new KeyboardUtil.OnOkClick() {
            @Override
            public void onOkClick() {
                isPay = computeRate();
            }
        });

        keyboardUtil.setOnCancelClick(new KeyboardUtil.onCancelClick() {
            @Override
            public void onCancellClick() {
                isPay = computeRate();
            }
        });

        editAmount.setNumberListener(new EasyMoneyEditText.NumberListener() {
            @Override
            public void exchange(String original, String formatted) {
                isPay = computeRate();
            }
        });

        editAmount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupKeyboard();
            }
        });

        txtFee.setText(String.format(feeStr, "0.00", "0.5%"));


    }

    @Override
    public void getParams() {
        Api.getService().getBankcardList(1, 20)
                .compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(this))
                .subscribe(new Consumer<HttpResult<StellarList>>() {
                    @Override
                    public void accept(HttpResult<StellarList> result) throws Exception {

                        if (result != null) {
                            List<BankCard> bankcards = result.data.bankcards;
                            bankCard = bankcards.get(0);
                            cardName.setText(bankCard.bank);
                            cardNumber.setText(bankCard.getCardNumber());
                            GlideApp.with(WithdrawActivity.this).load(bankCard.bankIcon).into(cardIcon);

                            bankAdapter = new BottomBankAdapter(WithdrawActivity.this, bankcards);

                            walletBalance.setMoneyText(OkSingleton.getInstance().getAssetBalance());

                            totalBalanceBigDecimal = new BigDecimal(OkSingleton.getInstance().getAssetBalance());
                            currency = OkSingleton.getInstance().getCurrencyCode();

                            coinPair = (currency + "_" + bankCard.cardAssetShort).toUpperCase();
//                            editAmount.setCurrencySymbol(currency);
                            walletBalance.setSizeCurrencySymbol(currency);
                            int drawableId = getResources().getIdentifier("ic_secondary_" + bankCard.cardAssetShort.toLowerCase(),
                                    "drawable", getPackageName());
                            txtPayBalance.setCurrencyWithdrawSymbol(bankCard.cardAssetShort, drawableId);

                            getRate(coinPair);
                        }


                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));

    }

    /**
     * 体现所有余额
     */
    @OnClick(R.id.txt_all)
    void all() {
        editAmount.setText(walletBalance.getValueString());
        isPay = computeRate();
    }

    /**
     * 选择提现银行卡
     */
    @OnClick(R.id.layout_bank)
    void selectedBank() {
        if (bankAdapter != null) {
            bankDialog.show(bankAdapter);
        }
    }

    /**
     * 弹出输入键盘
     */
    void popupKeyboard() {
        keyboardUtil.attachTo(editAmount);
    }

    /**
     * 确认交易
     */
    @OnClick(R.id.btn_confirm)
    void withdraw() {

        if (TextUtils.isEmpty(currency) || bankCard == null) {
            return;
        }

        if (!isPay) {
            return;
        }

        showPayKeyBoard();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bankDialog.closeDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddBankActivity.MANGER_CARD_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                BankCard card = data.getParcelableExtra("BankCard");
                selectBank(card);
                bankDialog.closeDialog();
            }
        }
    }

    /**
     * 选择银行
     *
     * @param card
     */
    @Override
    public void selectBank(BankCard card) {
        //TODO 更新UI
        bankCard = card;
        cardName.setText(card.bank);
        cardNumber.setText(card.getCardNumber());

        int drawableId = getResources().getIdentifier("ic_secondary_" + bankCard.cardAssetShort.toLowerCase(),
                "drawable", getPackageName());

        txtPayBalance.setCurrencyWithdrawSymbol(bankCard.cardAssetShort, drawableId);

        coinPair = (currency + "_" + bankCard.cardAssetShort).toUpperCase();

        GlideApp.with(WithdrawActivity.this).load(bankCard.bankIcon).into(cardIcon);

        getRate(coinPair);
    }


    /**
     * 选择资产网关
     *
     * @param gateway
     */
    @Override
    public void selectGateway(Gateway gateway) {

    }

    /**
     * 获取当前汇率
     * <p>
     * 选择银行卡时调用
     *
     * @param q
     */
    private void getRate(String q) {
        Api.getService().convert(q, "ultra")
                .compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(this))
                .subscribe(new Consumer<Map<String, String>>() {
                    @Override
                    public void accept(Map<String, String> map) throws Exception {
                        if (!map.isEmpty()) {//有汇率转换
                            Logger.d(map);
                            rateBigDecimal = new BigDecimal(map.get(q));
                            isPay = computeRate();
                        } else {//无汇率转换
                            rateBigDecimal = new BigDecimal(1);
                            isPay = computeRate();
                        }
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));
    }

    /**
     * 计算汇率
     */
    boolean computeRate() {
        //TODO 处理汇率转换 费率计算
        //没有获取汇率，直接返回
        if (is(rateBigDecimal).isNullOrZero()) {
            label_reminders.setVisibility(View.INVISIBLE);
            return false;
        }

        if (is(totalBalanceBigDecimal).isNullOrZero()) {
            label_reminders.setVisibility(View.VISIBLE);
            label_reminders.setText(zeroHint);
            return false;
        }

        String temp = editAmount.getValueString();
        BigDecimal receiveBigDecimal = new BigDecimal(temp);

        if (is(receiveBigDecimal).isNullOrZero()) {
            label_reminders.setVisibility(View.INVISIBLE);
            label_reminders.setText(reminderHint);
            return false;
        }

        if (is(receiveBigDecimal).isPositive() && is(receiveBigDecimal).lteq(totalBalanceBigDecimal)) {
            String str = rateBigDecimal
                    .multiply(receiveBigDecimal)
                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toString();
            txtPayBalance.setMoneyText(str);
            BigDecimal feeBigDecimal = new BigDecimal(0.005);
            String string = receiveBigDecimal
                    .multiply(feeBigDecimal)
                    .setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toString();
            txtFee.setVisibility(View.VISIBLE);
            txtFee.setText(String.format(feeStr, string, "0.5%"));
            label_reminders.setVisibility(View.INVISIBLE);
            return true;
        } else {
            label_reminders.setVisibility(View.VISIBLE);
            label_reminders.setText(reminderHint);
            return false;
        }
    }


    @Override
    public void onPasswordChange(String pwd) {

    }

    @Override
    public void onPasswordComplete(String pwd) {

        String amount = editAmount.getValueString();
        Map<String, String> params = new HashMap<>();
        params.put("currency", currency);
        params.put("amount", amount);
        params.put("card_id", bankCard.id + "");
        params.put("remark", "Withdraw");

        TransactionUtils.transaction(amount, "Withdraw")
                .flatMap(new Function<String, Publisher<HttpResult<PayResult>>>() {
                    @Override
                    public Publisher<HttpResult<PayResult>> apply(String sign) throws Exception {
                        params.put("stellar_trx_sign", sign);
                        return Api.getService().doWithdraw(params);
                    }
                }).compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(this))
                .subscribe(new Consumer<HttpResult<PayResult>>() {
                    @Override
                    public void accept(HttpResult<PayResult> httpResult) throws Exception {
                        PayResult result = httpResult.data;
                        result.errorMessage = httpResult.msg;
                        result.setFlag(WithdrawActivity.this,HomeCenter.SCHEME_WITHDRAW);
                        if (httpResult.code == 0) {
                            PayOkActivity.start(WithdrawActivity.this, result);
                        } else {
                            PayFailActivity.start(WithdrawActivity.this, result);
                        }
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        PayResult result = new PayResult(WithdrawActivity.this,HomeCenter.SCHEME_WITHDRAW);
                        result.errorMessage = throwable.getMessage();
                        PayFailActivity.start(WithdrawActivity.this, result);
                    }
                }));
    }

    @Override
    public void onForgetPwd() {

    }

    @Override
    public void onStop() {
        super.onStop();
        if (pinDialog != null) {
            pinDialog.dismiss();
        }
    }
}
